package cn.hzking.gjmall.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.WxLoginBean;
import cn.hzking.gjmall.delegates.main.CarDelegate;
import cn.hzking.gjmall.delegates.main.CategoryDelegate;
import cn.hzking.gjmall.delegates.main.HomeDelegate;
import cn.hzking.gjmall.delegates.main.MaterialDelegate;
import cn.hzking.gjmall.delegates.main.MyDelegate;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.Logger;
import cn.hzking.gjmall.utils.SPUtils;
import cn.hzking.gjmall.utils.SpPutUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.yokeyword.fragmentation.SupportFragment;

public class MainActivity extends ColorStatuBarActivity implements View.OnClickListener {
    @Bind(R.id.rl_home)
    RelativeLayout rlHome;//主页
    @Bind(R.id.rl_category)
    RelativeLayout rlCategory;//分类
    @Bind(R.id.rl_car)
    RelativeLayout rlCar;//购物车
    @Bind(R.id.rl_my)
    RelativeLayout rlMy;//我的
    @Bind(R.id.framelayout_main)
    FrameLayout framelayoutMain;
    @Bind(R.id.image_center)
    ImageView imageCenter;//素材
    @Bind(R.id.unread_num)
    TextView unreadNum;
    private SupportFragment[] mFragments = new SupportFragment[5];
    private SupportFragment currentDelegate;
    private int secletIndex = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initListener();
        initDelegates();
        refrsh();

    }

    private void initDelegates() {
        try {
            SupportFragment firstFragment = findFragment(HomeDelegate.class);
            if (firstFragment == null) {
                rlHome.setSelected(true);
                secletIndex = 1;
                mFragments[0] = new HomeDelegate();
                mFragments[1] = new CategoryDelegate();
                mFragments[2] = new MaterialDelegate();
                mFragments[3] = new CarDelegate();
                mFragments[4] = new MyDelegate();

                loadMultipleRootFragment(R.id.framelayout_main, 0,
                        mFragments[0],
                        mFragments[1],
                        mFragments[2],
                        mFragments[3],
                        mFragments[4]
                );
                currentDelegate = mFragments[0];
            } else {
                // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题
                // 这里我们需要拿到mFragments的引用
                mFragments[0] = firstFragment;
                mFragments[1] = findFragment(CategoryDelegate.class);
                mFragments[2] = findFragment(MaterialDelegate.class);
                mFragments[3] = findFragment(CarDelegate.class);
                mFragments[4] = findFragment(MyDelegate.class);
            }


        } catch (Exception e) {
            startActivity(new Intent(this, SplashActivity.class));
            finish();
        }

    }

    private void initListener() {
        rlHome.setOnClickListener(this);
        rlCategory.setOnClickListener(this);
        imageCenter.setOnClickListener(this);
        rlCar.setOnClickListener(this);
        rlMy.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        initButtom();
        switch (v.getId()) {
            case R.id.rl_home:
                rlHome.setSelected(true);
                mShowHideFragment(mFragments[0]);
                secletIndex = 1;
                break;
            case R.id.rl_category:
                rlCategory.setSelected(true);
                mShowHideFragment(mFragments[1]);
                secletIndex = 2;
                break;
            case R.id.image_center:
                mShowHideFragment(mFragments[2]);
                secletIndex = 3;
                break;
            case R.id.rl_car:
                rlCar.setSelected(true);
                mShowHideFragment(mFragments[3]);
                secletIndex = 4;
                break;
            case R.id.rl_my:
                rlMy.setSelected(true);
                mShowHideFragment(mFragments[4]);
                secletIndex = 5;
                break;


        }
    }

    private final void initButtom() {
        rlHome.setSelected(false);
        rlCategory.setSelected(false);
        rlCar.setSelected(false);
        rlMy.setSelected(false);
        imageCenter.setSelected(false);
    }

    private void mShowHideFragment(SupportFragment showDelegate) {
        try {
            if (currentDelegate != showDelegate) {
                showHideFragment(showDelegate, currentDelegate);
                currentDelegate = showDelegate;
            }
        } catch (Exception e) {
            Logger.e(e.getMessage());
            startActivity(new Intent(this, SplashActivity.class));
            finish();
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("index", secletIndex);
        outState.putLong("time", System.currentTimeMillis());

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        int index = savedInstanceState.getInt("index");
        long time = savedInstanceState.getLong("time");
        if ((System.currentTimeMillis() - time) > 30 * 60 * 1000) {//异常销毁大于半个小时
            startActivity(new Intent(this, SplashActivity.class));
            finish();
            return;
        }
        Log.e("hh", index + "");
        switch (index) {
            case 1:
                rlHome.setSelected(true);
                break;
            case 2:
                rlCategory.setSelected(true);
                break;
            case 3:
                break;
            case 4:
                rlCar.setSelected(true);
                break;
            case 5:
                rlMy.setSelected(true);
                break;
            default:
                startActivity(new Intent(this, SplashActivity.class));
                finish();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String s) {
        if ("goHome".equals(s)) {//返回首页
            if (currentDelegate != mFragments[0]) {
                initButtom();
                rlHome.setSelected(true);
                mShowHideFragment(mFragments[0]);
                secletIndex = 1;
            }
        } else if ("goCar".equals(s)) {//跳转到购物车
            if (currentDelegate != mFragments[3]) {
                initButtom();
                rlCar.setSelected(true);
                mShowHideFragment(mFragments[3]);
                secletIndex = 3;
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        setMainData();
    }

    private void setMainData() {
        if (SPUtils.getCarNum(this) == 0) {
            unreadNum.setVisibility(View.GONE);
        } else {

            unreadNum.setText(String.valueOf(SPUtils.getCarNum(this)));
        }
        if (SPUtils.getIsSeller(mContext)) {//如果是店主
            imageCenter.setSelected(true);
        } else {
            imageCenter.setSelected(false);

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        refrsh();
    }

    //刷新数据接口
    private void refrsh() {

        RetrofitFactory.getInstant().API()
                .refrsh()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<WxLoginBean>((Activity) mContext, false, false) {
                    @Override
                    protected void onSuccees(WxLoginBean wxLoginBean) throws Exception {
                        SpPutUtils.put(MainActivity.this, wxLoginBean);
                        //更新ui
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                setMainData();
                            }
                        });

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                    }

                    @Override
                    protected void onCodeError(WxLoginBean wxLoginBean) throws Exception {
                        super.onCodeError(wxLoginBean);
                    }
                });
    }

}





